package networld 
{
	import flash.net.NetStream;
	
	/**
	 * Class for working with players.
	 * NetPlayer is able to receive data
	 * from another players or broadcast data 
	 * to everybody
	 */
	internal class NetPlayer{
		
		private var world: NetWorld;
		private var rtmfpName: String;
		
		internal var isMaster: Boolean;
		
		
		private var stream: NetStream;
		private function get isLocal(): Boolean {
			return world.localPlayer == this;
		}
		
		
		public function NetPlayer(world: NetWorld, 
									farID: String = null) {
			this.world = world;
			this.isMaster = false;
			
			if (farID == null) {
				createOutputStream();
			}else {
				subscribeOnPlayer(farID);
			}
		}
		
		private function subscribeOnPlayer(farID: String): void {

			stream = new NetStream(world.rtmfpServer, farID);
			stream.client = this;
			stream.play("broadcast");
		}
		
		private function createOutputStream(): void {
			
			stream = new NetStream(world.rtmfpServer,
							NetStream.DIRECT_CONNECTIONS);
			stream.publish("broadcast");
		}
		internal function broadcastMessage(message: String): void {
			stream.send("onMessage", rtmfpName, message);
		}
		public function onMessage(farID: String, message: String): void {
			/* Transforming farID to our NetPlayer object */
			filterFarID = farID;
			const senders: Array = world.players.filter(filterByRtmfpName);
			
			var sender: NetPlayer;
			if (senders.length > 0)
				sender = senders[0];
			else
				return;
			
			/*Well done */
			var chatEvent: NetWorldEvent = 
				new NetWorldEvent(NetWorldEvent.CHAT_MESSAGE);
			
			chatEvent.messageSender = sender;
			chatEvent.messageText = message;
			world.dispatchEvent(chatEvent);
		}
		
		private var filterFarID: String;
		/* Gets from player's array, player with rtmgpName == farID */
		public function filterByRtmfpName(player: NetPlayer): Boolean {
			if (player.rtmfpName == filterFarID)
				return true;
			return false;
		}
		
	}

}